package com.zdl.mysmall.testservice.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.Build.VERSION_CODES.LOLLIPOP_MR1
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import android.util.Log
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.zdl.mysmall.testservice.MainActivity
import com.zdl.mysmall.testservice.MessageWrap
import org.greenrobot.eventbus.EventBus


class BackGroundService : Service() {

    var notification: Notification? = null
    private var mContext: Context? = null
    private var uploadGpsThread: Thread? = null
    private var bgmediaPlayer: MediaPlayer? = null
    private var isrun = true

    //声明AMapLocationClient类对象
    var mLocationClient: AMapLocationClient? = null
    //声明定位回调监听器


    //声明AMapLocationClientOption对象
    var mLocationOption: AMapLocationClientOption? = null

    //版本兼容
    override fun onBind(intent: Intent?): IBinder? {
        throw  UnsupportedOperationException("Not yet implemented")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mContext = this;

        //初始化定位
        mLocationClient = AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient!!.setLocationListener {
            Log.e("tag",it.latitude.toString())
            EventBus.getDefault().post(MessageWrap());
        };
//初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */


        val aMapLocationClientOption = mLocationOption?.run {
            locationPurpose = AMapLocationClientOption.AMapLocationPurpose.Transport;
            //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
            locationMode = AMapLocationClientOption.AMapLocationMode.Battery_Saving;
            //设置定位模式为AMapLocationMode.Device_Sensors，仅设备模式。
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy;
            //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
            interval = 1000;
            isNeedAddress = true;
            isNeedAddress = true
            setMockEnable(true);
        }
        mLocationClient?.run {
            setLocationOption(aMapLocationClientOption);
            stopLocation()
            startLocation()
        }
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            mContext, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT
        )

        //1.通知栏占用，不清楚的看官网或者音乐类APP的效果
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O && Build.VERSION.SDK_INT >= LOLLIPOP_MR1) {
            notification = NotificationCompat.Builder(mContext)
                .setContentTitle("GPS测试")
                .setContentText("GPS测试内容")
                .setSmallIcon(android.R.drawable.stat_sys_download_done)
                .setContentIntent(pendingIntent).build()

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT <= LOLLIPOP_MR1) {
            notification = Notification.Builder(mContext)
                .setAutoCancel(false)
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.stat_sys_download_done)
                .setWhen(System.currentTimeMillis())
                .build()
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = mContext?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val CHANNEL_ID = "my_channel_01"
            val name = "my_channel"
            val Description = "This is my channel"
            val importance = NotificationManager.IMPORTANCE_LOW
            val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
            mChannel.description = Description
            mChannel.enableLights(false)
            mChannel.setSound(null, null);
            mChannel.enableVibration(false);
            mChannel.vibrationPattern = longArrayOf();
//            mChannel.enableVibration(true)//震动
//            mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)//震动
            mChannel.setShowBadge(false)
            notificationManager.createNotificationChannel(mChannel)
            notification = NotificationCompat.Builder(mContext as BackGroundService, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.stat_sys_download_done)
                .setContentTitle("GPS测试")
                .setContentText("GPS测试内容")
                .setContentIntent(pendingIntent)
                .build()

        }
        /*使用startForeground,如果id为0，那么通知栏不显示将不会显示*/
        startForeground(0, notification)

        //2.开启线程（或者需要定时操作的事情）
        if (uploadGpsThread == null) {
            uploadGpsThread = Thread(Runnable {
                //这里用死循环就是模拟一直执行的操作
                while (isrun) {

                    //你需要执行的任务
//                    doSomething()

                    try {
                        Thread.sleep(10000L)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                }
            })
        }
        //3.最关键的神来之笔，也是最投机的动作，没办法要骗过CPU
        //这就是播放音乐类APP不被杀的做法，自己找个无声MP3放进来循环播放
        if (bgmediaPlayer == null) {
            bgmediaPlayer = MediaPlayer.create(this, com.zdl.mysmall.testservice.R.raw.wusheng);

            bgmediaPlayer?.run {
                isLooping = true;
                this.start();
            }


        }


        return START_STICKY

    }


    override fun onDestroy() {
        super.onDestroy()
        isrun = false;
        stopForeground(true);
        bgmediaPlayer?.release();
        stopSelf();
        super.onDestroy();
    }
}